package guestbook;
import javax.servlet.http.*;

/*
 * this class will run based on the cron jobs. it fetches the links to statistics
 * and stores them in the DB
 */

public class gettingTotoStats extends HttpServlet 
{    
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	 {
		try
		{
			
			totoStat stat=null; //this var will hold the stats data
			Boolean flag=true;
			int i=0;
			
			//the following loop iterates at most 5 times, stops when stat is ok
			while ((stat==null)&& (i<5)){
				MyUrl url=new MyUrl("http://www.toto.org.il/85_normal.asp");
				String str=	parsingSites.createStringFromHtml(url);		
				stat=parseLinks(str);
				i++;
			}
			
			//check the object stat was successfully created
			if (stat==null){
				resp.getWriter().println("error");
				flag=false;
				return;				
			}			
			
			//the following part saves the totoStat array in the DB
			DBMethods.saveInDB(stat,flag);		
			
			/* returns success to caller if all is well*/
			resp.setContentType("text/plain;charset=UTF-8");
			resp.getWriter().println("success");
		
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}		
	}
	
	
	//this method gets a string which is a full html from toto site and parses it.
	private totoStat parseLinks(String str){
		if (str==null) return null;
		totoStat stat=new totoStat(new String[16]);
		
		//currently str holds the entire source of toto site, now we parse it
		String substr_help=str.substring(str.indexOf("showStat")+10);
		int closeIndex=substr_help.indexOf("\'");
		String substr=substr_help.substring(0,closeIndex);
		stat.getStat()[0]="http://www.toto.org.il/totodata/teamStat.asp?detail="+substr;
		
		//the following loop parses the toto site. in the end, the result array contains the required info.
		for (int i=1;i<16;i++){
			
			//substr_help=substr_help.substring(substr_help.indexOf("showStat")+10);
			substr_help=substr_help.substring(substr_help.indexOf("showStat")+10);
			closeIndex=substr_help.indexOf("\'");
			stat.getStat()[i]="http://www.toto.org.il/totodata/teamStat.asp?detail="+substr_help.substring(0,closeIndex);
		}
		
		return stat;
		
	}
			
}
